/*
 * Copyright (c) 2006-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.gclient;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import java.util.TimeZone;

import org.panteleyev.utilities.xml.XMLHelpers;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.gdata.data.Category;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Link;
import com.google.gdata.data.PlainTextConstruct;

public class GBEntry extends GBBaseEntry {
    private GBlog blog;
    private int _commentsCount;
    private URL _entryURL;

    /**
     * Creates a new instance of GBEntry
     */
    public GBEntry() {
        super(new Entry());
    }

    public GBEntry(GBlog blog) {
        super(new Entry());
        this.blog = blog;
        _entryURL = null;
    }

    public GBEntry(GBlog blog, Entry entry) {
        super(entry);
        this.blog = blog;

        Link link = entry.getLink("alternate", "text/html");
        try {
            _entryURL = (link == null)? null : new URL(link.getHref());
        } catch (MalformedURLException e) {
            _entryURL = null;
        }
    }

    public GBlog getBlog() {
        return blog;
    }

    public void setBlog(GBlog blog) {
        this.blog = blog;
    }

    public URL getEntryURL() { return _entryURL; }

    public int getCommentsCount() { return _commentsCount; }
    void setCommentsCount(int n) { _commentsCount = n; }

    public String getBlogID() {
        return (blog == null)? null : blog.getID();
    }

    public void setDate(Date date) {
        getEntry().setPublished(new DateTime(date, TimeZone.getDefault()));
    }

    public void setSubject(String subj) {
        getEntry().setTitle(new PlainTextConstruct(subj));
    }

    public ArrayList<String> getLabels() {
        ArrayList<String> labels = new ArrayList<>();
        Set<Category> cats = getEntry().getCategories();
        for (Category cat : cats) {
            labels.add(cat.getTerm());
        }

        return labels;
    }

    public void setLabels(ArrayList<String> labels) {
        Set<Category> cats = getEntry().getCategories();

        cats.clear();

        for (String label : labels) {
            Category c = new Category();
            c.setScheme("http://www.blogger.com/atom/ns#");
            c.setTerm(label);
            cats.add(c);
        }
    }

    URL getCommentsFeedURL() {
        try {
            return new URL(GBAccount.FEED_URL + getBlog().getID() + "/" + getId() + "/comments/default");
        } catch (MalformedURLException e) {
            return null;
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if ((obj == null) || !(obj instanceof GBEntry)) {
            return false;
        }

        GBEntry entry = (GBEntry)obj;
        return (getId().equals(entry.getId()) && getBlogID().equals(entry.getBlogID()));
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 17 * hash + (this.getId() != null ? this.getId().hashCode() : 0);
        hash = 17 * hash + (this.getBlogID() != null ? this.getBlogID().hashCode() : 0);
        return hash;
    }

    public void toXML(Document doc) {
        Element root = doc.createElement("entry");
        doc.appendChild(root);

        root.setAttribute("draft", Boolean.toString(isDraft()));
        XMLHelpers.setDateAttribute(root, "date", getDate());

        ArrayList<String> labels = getLabels();
        for (String label : labels) {
            Element e = doc.createElement("label");
            e.setAttribute("name", label);
            root.appendChild(e);
        }

        Element subject = doc.createElement("subject");
        subject.appendChild(doc.createTextNode(getSubject()));
        root.appendChild(subject);

        Element body = doc.createElement("body");
        body.appendChild(doc.createTextNode(getBody()));
        root.appendChild(body);
    }

    public void fromXML(Document doc) {
        NodeList children = doc.getElementsByTagName("entry");
        if (children.getLength() > 0) {
            fromXML((Element)children.item(0));
        }
    }

    public void fromXML(Element root) {
        setDraft(XMLHelpers.getBooleanAttribute(root, "draft", false));
        setDate(XMLHelpers.getDateAttribute(root, "date", new Date()));

        ArrayList<String> labels = new ArrayList<>();

        NodeList children = root.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node instanceof Element) {
                Element element = (Element)node;

                String tagName = element.getTagName();

                if (tagName.equals("subject")) {
                    setSubject(XMLHelpers.getTextChild(element));
                    continue;
                }

                if (tagName.equals("body")) {
                    setBody(XMLHelpers.getTextChild(element));
                    continue;
                }

                if (tagName.equals("label")) {
                    String labelStr = element.getAttribute("name");
                    if ((labelStr != null) && (labelStr.length() != 0)) {
                        labels.add(labelStr);
                    }
                    continue;
                }
            }
        }

        setLabels(labels);
    }
}
